package com.ydy.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ydy.common.constant.Constant;
import com.ydy.common.model.User;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

public class JwtTokenUtil {


    //公钥
    public  static String SECRET = "ydy-SpringCloud";

    // 有效时长毫秒数
    private static final long EXPIRE_TIME = 30 * 60 * 1000;


    /**
     * 生成token
     * @return
     */
    public static String creatToken(User user){
        //签发时间
        Date date = new Date();

        Map<String,Object> map = new LinkedHashMap<>();
        map.put("alg","HS256");
        map.put("typ","JWT");
        //用户名
        String userName = user.getUserName();
        //用户Id
        String userCode = user.getUserCode();

        //生成token
        String token = JWT.create()
                .withHeader(map)
                .withClaim(Constant.USER_CODE,userCode)
                .withClaim(Constant.USER_NAME,userName)
                .withIssuedAt(date)
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    public static Map<String, Claim> verifyToken(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
        try{
            jwt = jwtVerifier.verify(token);
        }catch (Exception e ){
            //TODO
        }

        return jwt.getClaims();
    }
}